package com.gxc.service.goods.controller;

import com.gxc.service.common.model.ServerResponse;
import com.gxc.service.goods.model.dto.GetFeignTestDto;
import com.gxc.service.goods.model.entity.ProductEntity;
import com.gxc.service.goods.repository.ProductRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试Controller.
 *
 * @author GongXincheng
 * @since 2019-11-08 18:03
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Resource
    private ProductRepository productRepository;

    /**
     * 批量新增
     */
    @GetMapping("/add")
    public ServerResponse<List<ProductEntity>> add() {
        List<ProductEntity> entityList = new ArrayList<>(10);
        for (int i = 1; i < 10; i++) {
            ProductEntity entity = new ProductEntity();
            entity.setDisplayName("iphone_" + i);
            entity.setProdName("iphone_" + i + "_pro");
            entityList.add(entity);
        }
        entityList = productRepository.saveAll(entityList);
        return ServerResponse.ok(entityList);
    }

    /**
     * 根据id查询.
     */
    @GetMapping("/{id}")
    public ServerResponse<ProductEntity> findById(@PathVariable Long id) {
        return ServerResponse.ok(productRepository.findById(id).orElse(null));
    }

    /**
     * 模糊查询
     */
    @GetMapping("/search")
    public ServerResponse<List<ProductEntity>> likeSearch(@RequestParam String name) {
        List<ProductEntity> result = productRepository.findByProdNameLike("%" + name + "%");
        return ServerResponse.ok(result);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public ServerResponse<ProductEntity> save(@RequestBody ProductEntity entity) {
        return ServerResponse.ok(productRepository.save(entity));
    }


    @GetMapping("/feign/get-test")
    public ServerResponse<GetFeignTestDto> feignGetTest(GetFeignTestDto dto) {
        System.out.println(dto);
        return ServerResponse.ok(dto);
    }
}
